package com.example.project.projectspringcloud.controller.admin.workorder;

import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Dictionary;
import com.example.project.projectspringcloud.entity.workorder.WorkOrder;
import com.example.project.projectspringcloud.service.sys.SysDictionaryService;
import com.example.project.projectspringcloud.service.workorder.WorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Api(tags = "管理员工单系统")
@Controller
@RequestMapping(value = "/admin/workorder")
public class AdminWorkOrderController {

    private final Logger logger = LoggerFactory.getLogger(AdminWorkOrderController.class);

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private SysDictionaryService sysDictionaryService;

    @ApiOperation(value = "工单列表", notes = "返回工单列表")
    @RequestMapping(value = {"", "/list"})
    public String list(WorkOrder workOrder, Page page, Model model) {

        model.addAttribute("page", new Page<WorkOrder>(workOrderService.list(workOrder, page)));
        model.addAttribute("workOrder", workOrder);
        return "admin/workorder/workorder-list";
    }

    @ApiOperation(value = "获取表单信息", notes = "返回表单页面")
    @GetMapping(value = "/form")
    public String form(@RequestParam(value = "id", required = false) Integer id, Model model) {
        if (id != null) {
            model.addAttribute("workOrder", workOrderService.get(new WorkOrder(id)));
        }

        model.addAttribute("workOrderStatus", sysDictionaryService.list(new Dictionary("work-order-status"), null));

        return "admin/workorder/workorder-form";
    }

    @ApiOperation(value = "API完结工单", notes = "完结工单")
    @PostMapping(value = "/finish/{id}")
    @ResponseBody
    public RespBody finish(@PathVariable("id") Integer id) {

        WorkOrder workOrder = workOrderService.get(new WorkOrder(id));
        if (workOrder != null) {
            try {
                // 设置成结单
                workOrder.setStatus(2);
                workOrderService.save(workOrder);
                return RespBody.ok(true);
            } catch (Exception e) {
                logger.error("AdminWorkOrderController - finish - error", e);
                return RespBody.error("操作失败");
            }
        } else {
            return RespBody.error("工单不存在");
        }
    }
}
